package com.yamanyar.weebill.view;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;

import com.yamanyar.weebill.domain.User;
import com.yamanyar.weebill.service.UserService;

/**
 * Logs in or logs out an user.
 * 
 * Created in Jun 28, 2008.
 * 
 * @author Kaan Yamanyar
 */
@org.springframework.stereotype.Component("userSession")
@Scope("session")
public class UserSession implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6785907946599065081L;

	private UserService userService;

	private User user = null;

	private String username = null;

	private String password = null;

	private String rightMenu = "blank.xhtml";

	public String getRightMenu() {
		return rightMenu;
	}

	public void setRightMenu(String rightMenu) {
		this.rightMenu = rightMenu;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Autowired
	public UserSession(UserService userService) {
		this.userService = userService;
	}

	public String login() {
		User userFound = userService.findByMail(username);
		if (userFound != null && password.equals(userFound.getPassword())) {
			this.user = userFound;
		} else {

			FacesMessage facesMessage = new FacesMessage(
					FacesMessage.SEVERITY_ERROR, "Login failed.",
					"User does not exists or password failed.");
			FacesContext.getCurrentInstance().addMessage("loginForm",
					facesMessage);
		}
		this.username = null;
		this.password = null;
		return null;
	}

	public String logout() {
		this.user = null;
		this.username = null;
		this.password = null;
		return null;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
